﻿Imports System
Imports System.Runtime.CompilerServices
Imports System.Transactions

Namespace System.Workflow.Runtime.Hosting
    Public MustInherit Class WorkflowCommitWorkBatchService
        Inherits WorkflowRuntimeService
        ' Methods
        Protected Sub New()
        End Sub

        Protected Friend Overridable Sub CommitWorkBatch(ByVal commitWorkBatchCallback As CommitWorkBatchCallback)
            Dim transactionToUse As Transaction = Nothing
            If (Nothing Is Transaction.Current) Then
                transactionToUse = New CommittableTransaction
            Else
                transactionToUse = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete)
            End If
            Try 
                [Using] scope As TransactionScope = New TransactionScope(transactionToUse)
                    commitWorkBatchCallback.Invoke
                    scope.Complete
                End [Using]
                Dim transaction2 As CommittableTransaction = [TryCast](transactionToUse,CommittableTransaction)
                If (Not transaction2 Is Nothing) Then
                    transaction2.Commit
                End If
                Dim transaction3 As DependentTransaction = [TryCast](transactionToUse,DependentTransaction)
                If (Not transaction3 Is Nothing) Then
                    transaction3.Complete
                End If
            Catch exception As Exception
                transactionToUse.Rollback(exception)
                Throw
            Finally
                If (Not transactionToUse Is Nothing) Then
                    transactionToUse.Dispose
                End If
            End Try
        End Sub


        ' Nested Types
        Public Delegate Sub CommitWorkBatchCallback()
    End Class
End Namespace

